//
//  DataBaseManager.m
//  FMDB-名片
//
//  Created by Hello Cai on 16/2/18.
//  Copyright © 2016年 Hello Cai. All rights reserved.
//

#import "DataBaseManager.h"
#import "FMDatabase.h"

static NSString *const TABLE_Persons = @"PersonTable";

@interface DataBaseManager ()

@property(nonatomic,strong)FMDatabase *fmdatabase;

@end

@implementation DataBaseManager

+(instancetype)shareDatabase{
    //静态指针
    static DataBaseManager *single =nil;
    //类似一个线程锁的效果
    static dispatch_once_t token;
    //保证block内部的代码在整个应用程序当中只会执行一次
    dispatch_once(&token, ^{
        single = [DataBaseManager new];
    });
    return single;
}

//重写init方法
-(instancetype)init{
    self = [super init];
    if(self){
        //数据路径
        NSString *dataPath = [NSHomeDirectory() stringByAppendingString:@"/Documents/new.rdb"];
        //创建并且打开数据库
        self.fmdatabase = [[FMDatabase alloc] initWithPath:dataPath];
        NSLog(@"databasePath= %@",dataPath);
        
        if(![_fmdatabase open]){
            NSLog(@"打开数据库失败");
        }
        
        //创建表
        NSString *sql = [NSString stringWithFormat:@"create table if not exists %@ (id integer primary key autoincrement,name text, phoneNumber text,headImage BLOB)", TABLE_Persons];
        if(![_fmdatabase executeUpdate:sql]){
            NSLog(@"创建表失败");
        }
    }
    return self;
}
-(void)insertPersonModel:(Person *)model{
    NSString *sql = [NSString stringWithFormat:@"insert into %@ (name,phoneNumber,headImage) values (?,?,?)", TABLE_Persons];
    if (![self.fmdatabase executeUpdate:sql, model.nameStr,model.phoneStr,model.imageData]) {
        NSLog(@"插入失败");
    }
}
-(NSArray *)searchFromDatabase{
    NSString *sql = [NSString stringWithFormat:@"select * from %@",TABLE_Persons];
    FMResultSet *set = [self.fmdatabase executeQuery:sql];
    NSMutableArray *personDetailArr = [NSMutableArray new];
    while ([set next]) {
        Person *per = [Person new];
        per.nameStr = [set stringForColumn:@"name"];
        per.phoneStr = [set stringForColumn:@"phoneNumber"];
        per.imageData = [set dataForColumn:@"headImage"];
        [personDetailArr addObject:per];
    }
    //返回加载完成的数据
    return personDetailArr;
}
-(void)deletePerson:(Person *)model{
    NSString *sql = [NSString stringWithFormat:@"delete from %@ where name=? and phoneNumber=? and headImage=?", TABLE_Persons];
    if (![self.fmdatabase executeUpdate:sql, model.nameStr, model.phoneStr, model.imageData]) {
        NSLog(@"删除失败");
    }
}
//修改操作
-(void)updatePerson:(Person *)newModel oldModel:(Person *)oldModel{
    NSString *sql = [NSString stringWithFormat:@"update %@ set name=?, phoneNumber=?, headImage=? where name=? and phoneNumber=? and headImage=?", TABLE_Persons];
    if (![self.fmdatabase executeUpdate:sql, newModel.nameStr, newModel.phoneStr, newModel.imageData, oldModel.nameStr, oldModel.phoneStr, oldModel.imageData]) {
        NSLog(@"更新失败");
    }
}
@end
